<!-- subpkg_consult/room/index.vue -->
<script lang="ts" setup>
  import { orderDetailApi, uploadImageApi } from '@/api/consult'
  import useUserStore from '@/stores/user'
  import { onLoad } from '@dcloudio/uni-app'
  import { io, type Socket } from 'socket.io-client'
  import RoomStatus from './components/room-status.vue'
  import { nextTick, ref } from 'vue'
  import type { OrderDetail } from '@/types/consult'
  import type { Datum, MsgItem } from '@/types/room'
  import PatientInfo from './components/patient-info.vue'
  import NotifyInfo from './components/notify-info.vue'
  import MessageInfo from './components/message-info.vue'
  import PrescriptionInfo from './components/prescription-info.vue'
  import RateInfo from './components/rate-info.vue'

  // 收集数据,  监听回车提交  准备用户的id

  const store = useUserStore()

  const props = defineProps<{ orderId: string; payResult: string }>()

  const msgList = ref<MsgItem[]>([])

  // let定义变量和类型
  let socket: Socket

  onLoad(() => {
    if (props.payResult === 'false') {
      uni.switchTab({
        url: '/pages/my/my',
      })

      return
    }

    // 连接到服务器
    // 赋值
    socket = io('https://consult-api.itheima.net', {
      auth: { token: 'Bearer ' + store.token },
      query: { orderId: props.orderId },
      transports: ['websocket', 'polling'],
      timeout: 5000,
    })

    socket.on('connect', () => {
      console.log('连接成功')
    })

    // 监听订单状态改变
    // emit('statusChange')
    socket.on('statusChange', (res) => {
      getOrderInfo()
    })

    // 1. 监听服务器发来的聊天记录
    socket.on('chatMsgList', (res) => {
      console.log('收到服务器发来的聊天记录', res)
      if (res.code !== 10000) return
      res.data.forEach((item: Datum) => {
        // 4. 保存消息
        msgList.value.push(
          { msgType: 31, msg: { content: item.createTime }, id: item.createTime },
          ...item.items!
        )
      })
      // 每次收到消息, 滚动到底部
      nextTick(() => {
        lastId.value = 'xxx' + (msgList.value.length - 1)
      })
    })

    // 监听医生发来的消息
    socket.on('receiveChatMsg', (res) => {
      console.log('收到医生发来消息', res)
      // 2. 追加到消息列表中
      msgList.value.push(res)
      // 每次收到消息, 滚动到底部
      nextTick(() => {
        lastId.value = 'xxx' + (msgList.value.length - 1)
      })
    })
  })

  const orderInfo = ref({} as OrderDetail)
  // 获取订单详情
  const getOrderInfo = async () => {
    const res = await orderDetailApi(props.orderId)
    orderInfo.value = res
  }

  onLoad(() => {
    getOrderInfo()
  })

  const contentText = ref('')
  const onSendText = () => {
    // 3. 发消息
    socket.emit('sendChatMsg', {
      // 发送人的id
      from: store.userId,
      // 医生的id
      to: orderInfo.value.docInfo.id,
      // 文字消息类型
      msgType: 1,
      msg: {
        content: contentText.value,
      },
    })

    // 清空输入框
    contentText.value = ''
  }

  const onSendImage = async () => {
    if (orderInfo.value?.status !== 3) {
      return uni.showToast({ title: '医生当前不在线!' })
    }

    //  uni.chooseImage
    const res = await uni.chooseImage({ count: 1 })
    console.log('res  ----->  ', res)

    // 上传成功后, 得到一个在url地址

    const data = await uploadImageApi(res.tempFilePaths[0])
    console.log('data  ----->  ', data)

    // 发送给医生

    socket.emit('sendChatMsg', {
      // 发送人的id
      from: store.userId,
      // 医生的id
      to: orderInfo.value.docInfo.id,
      // 图片消息类型
      msgType: 4,
      msg: {
        picture: {
          id: data.id,
          url: data.url,
        },
      },
    })
  }
  // 消息滚动到最后
  // 准备ref 用来保存子元素的id
  const lastId = ref('')
</script>

<template>
  <view class="room-page">
    <RoomStatus :status="orderInfo.status" :countdown="orderInfo.countdown" />
    <scroll-view
      scroll-with-animation
      refresher-enabled
      refresher-background="#f2f2f2"
      scroll-y
      style="flex: 1; overflow: hidden"
      :scroll-into-view="lastId"
    >
      <view class="message-container">
        <!-- 此处将来填充更多代码... -->
        <!--  v-for渲染消息列表 -->
          <!-- 给scroll-view的每个子元素, 分配id -->
        <view v-for="(item,index) in msgList" :key="item.id" :id="'xxx' + index">
          <!-- msgType为21时, 显示患者信息卡片 -->
          <!--  父传子 -->
          <PatientInfo :info="item.msg?.consultRecord" v-if="item.msgType === 21" />
          <NotifyInfo v-if="item.msgType! >= 31" :type="item.msgType!">
            <!--  传入系统消息内容 -->
            {{ item.msg?.content }}
          </NotifyInfo>
          <MessageInfo
            :info="item"
            :type="item.msgType"
            v-if="item.msgType === 1 || item.msgType === 4"
          />
          <PrescriptionInfo v-if="item.msgType === 22" :info="item.msg!" />
          <RateInfo
            :order-id="orderId"
            :doc-id="orderInfo.docInfo?.id"
            v-if="item.msgType === 23 || item.msgType === 24"
            :type="item.msgType"
            :info="item.msg!"
          />
        </view>
      </view>
    </scroll-view>

    <!-- 发送消息 -->
    <view class="message-bar">
      <template v-if="true">
        <uni-easyinput
          @confirm="onSendText"
          :disabled="orderInfo.status !== 3"
          v-model="contentText"
          :clearable="false"
          :input-border="false"
          placeholder-style="font-size: 32rpx; color: #c3c3c5;"
          placeholder="问医生"
        />
        <view class="image-button">
          <uni-icons size="40" color="#979797" type="image" @click="onSendImage"></uni-icons>
        </view>
      </template>
      <button v-else class="uni-button">咨询其它医生</button>
    </view>
  </view>
</template>

<style lang="scss">
  @import './room.scss';
</style>
